/*
 ******************************************************************************
 * Parts of this code sample are licensed under Apache License, Version 2.0   *
 * Copyright (c) 2009, Android Open Handset Alliance. All rights reserved.    *
 *																			  *																			*
 * Except as noted, this code sample is offered under a modified BSD license. *
 * Copyright (C) 2010, Motorola Mobility, Inc. All rights reserved.           *
 * 																			  *
 * For more details, see MOTODEV_Studio_for_Android_LicenseNotices.pdf        * 
 * in your installation folder.                                               *
 ******************************************************************************
 */
package com.example.kalapp;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import com.example.kalapp.Food;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class DatabaseHandler extends SQLiteOpenHelper {

	private static String DB_PATH = "/data/data/com.example.kalapp/databases/";

	private static String DB_NAME = "kalAppDb.db";
	
	private static final int DATABASE_VERSION = 1;
	
	private static final String TABLE_MADVARE = "madvare";
	
	private static final String TABLE_PERSONINFO = "personinfo";
	
	public static final String ID = "id";
	public static final String NAVN = "navn";
	public static final String TYPE = "type";
	public static final String KALORIER = "kalorier";
	public static final String FEDT = "fedt";
	public static final String PROTEIN = "protein";

	private final Context myContext;
	
	private SQLiteDatabase myDataBase;

	
	public DatabaseHandler(Context context) {

		super(context, DB_NAME, null, DATABASE_VERSION);
		this.myContext = context;
	}

	public DatabaseHandler(Context context, boolean copyDatabase) {

		this(context);
		if (copyDatabase) {
			copyDatabaseFile();
		}
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_MADVARE);

		onCreate(db);
	}
	
	
	public List<Food> getAllFoods() {
		List<Food> foodList = new ArrayList<Food>();
		
		String selectQuery = "SELECT  * FROM " + TABLE_MADVARE;

		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);

		if (cursor.moveToFirst()) {
			do {
				Food food = new Food();
				food.setID(Integer.parseInt(cursor.getString(0)));
				food.setName(cursor.getString(1));
				food.setType(cursor.getString(2));
				food.setKalorier(cursor.getDouble(3));
				food.setFedt(cursor.getDouble(4));
				food.setProtein(cursor.getDouble(5));
				
				foodList.add(food);
			} while (cursor.moveToNext());
		}
		return foodList;
	}
	
	public List<String> getAllNames(){
		String selectQuery = "SELECT navn FROM " + TABLE_MADVARE;

		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);
		ArrayList<String> nameList = new ArrayList<String>();
		
            while(cursor.moveToNext())
            {
            	nameList.add(cursor.getString(cursor.getColumnIndex("navn")));
            }
            
		return nameList;
}
	
	public void copyDatabaseFile() {

		// variables
		InputStream myInput = null;
		OutputStream myOutput = null;
		SQLiteDatabase database = null;

		// only proceed in case the database does not exist
		if (!checkDataBaseExistence()) {
			// get the database
			database = this.getReadableDatabase();
			try {
				// Open your local db as the input stream
				myInput = myContext.getAssets().open(DB_NAME);

				// Path to the just created empty db
				String outFileName = DB_PATH + DB_NAME;

				// Open the empty db as the output stream
				myOutput = new FileOutputStream(outFileName);

				// transfer bytes from the input file to the output file
				byte[] buffer = new byte[1024];
				int length;
				while ((length = myInput.read(buffer)) > 0) {
					myOutput.write(buffer, 0, length);
				}
			} catch (FileNotFoundException e) {
				// handle your exception here
			} catch (IOException e) {
				// handle your exception here
			} finally {
				try {
					// Close the streams
					myOutput.flush();
					myOutput.close();
					myInput.close();
					// close the database in case it is opened
					if (database != null && database.isOpen()) {
						database.close();
					}

				} catch (Exception e) {
					// handle your exception here
				}
			}
		}
	}

	  
	private boolean checkDataBaseExistence() {

		// database to be verified
		SQLiteDatabase dbToBeVerified = null;

		try {
			// get database path
			String dbPath = DB_PATH + DB_NAME;
			// try to open the database
			dbToBeVerified = SQLiteDatabase.openDatabase(dbPath, null,
					SQLiteDatabase.OPEN_READONLY);

		} catch (SQLiteException e) {
			// do nothing since the database does not exist
		}

		// in case it exists, close it
		if (dbToBeVerified != null) {
			// close DB
			dbToBeVerified.close();

		}

		// in case there is a DB entity, the DB exists
		return dbToBeVerified != null ? true : false;
	}
	
	 public void open() throws SQLException{
		 
	        String myPath = DB_PATH + DB_NAME;
	    	myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
	    }
	 
	 
	 @Override
		public synchronized void close() {
	 
	    	    if(myDataBase != null)
	    		    myDataBase.close();
	 
	    	    super.close();
	 
		}
}
